<template>
  <div class="item-list">
    <van-list class="horizontal-list" style="flex-direction: row!important;">
      <van-cell v-for="item in items" :key="item.id" class="horizontal-cell" is-horizontal>
        <template #title>
          <div class="item-title">{{ item.name }}</div>
          <div class="item-price">{{ item.price }} ETH</div>
        </template>
        <template #default>
          <div class="item-description">{{ item.description }}</div>
          <div class="item-seller">卖家: {{ item.seller }}</div>
          <div class="item-status">{{ item.isSold? '已售出' : '未售出' }}</div>
          <van-button type="primary" @click="buyProduct(item.id)" v-if="!item.isSold" class="van-button">购买</van-button>
        </template>
      </van-cell>
    </van-list>
    <div v-if="purchaseMessage" :class="purchaseMessage.type === 'success'? 'success-message' : 'error-message'">
      {{ purchaseMessage.text }}
    </div>
    <van-loading v-if="isLoading" color="black" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import useWeb3 from '../util.js';
import { List, Cell, Button } from 'vant';

export default {
  components: {
    'van-list': List,
    'van-cell': Cell,
    'van-button': Button,
  },
  name: 'ItemView',
  setup() {
    const items = ref([]);
    const { contract, web3 } = useWeb3();
    const purchaseMessage = ref({ type: '', text: '' });
    const isLoading = ref(false);

    const buyProduct = async (productId) => {
      isLoading.value = true;
      try {
        const accounts = await web3.eth.requestAccounts();
        const buyerAccount = accounts[0];
        const itemToBuy = items.value.find(item => item.id === productId);
        if (!itemToBuy) {
        throw new Error('找不到对应的商品信息，请刷新页面重试。');
        }

        const gasPrice = web3.utils.toWei('10', 'gwei');
        const tx = await contract.methods.buyItem(productId).send({
          from: buyerAccount,
          value: web3.utils.toWei(itemToBuy.price.toString(), 'ether'),
          gasPrice: gasPrice
        });

        console.log('购买交易成功，交易哈希:', tx.transactionHash);
        purchaseMessage.value = { type: 'success', text: '购买成功！' };
      } catch (error) {
        console.error('购买商品出错:', error);
        if (error.message.includes('Insufficient funds')) {
          purchaseMessage.value = { type: 'error', text: '余额不足，请确保账户中有足够的资金来购买该商品。' };
        } else if (error.message.includes('Item does not exist or is already sold')) {
          purchaseMessage.value = { type: 'error', text: '该商品不存在或已售出，请选择其他商品。' };
        } else {
          purchaseMessage.value = { type: 'error', text: '购买商品时出现未知错误，请检查网络及相关配置。' };
        }
      } finally {
        isLoading.value = false;
      }
    };

    onMounted(async () => {
      try {
        const itemsData = await contract.methods.getItems().call();
        console.log("获取到的商品数据:", itemsData);
        items.value = itemsData.map(item => ({
          id: item.id,
          name: item.name,
          description: item.description,
          price: item.price,
          seller: item.seller,
          isSold: item.isSold,
        }));
      } catch (error) {
        console.error('获取商品信息出错:', error);
      }
    });

    return {
      items,
      buyProduct,
      purchaseMessage,
      isLoading
    };
  },
};
</script>

<style scoped>
.item-list {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  padding: 30px;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.horizontal-list {
  width: 100%;
}

.horizontal-cell {
  background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  border-radius: 15px;
  padding: 20px;
  width: 80%; ;
  transition: transform 0.3s, box-shadow 0.3s;
  color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-align: left;
  margin-bottom: 30px;
  margin-right: 30px;
  margin-left: 130px;
}
.horizontal-cell:last-child {
  margin-right: 0;
}
@media (max-width: 768px) {
.horizontal-cell {
    width: calc(50% - 20px);
  }
}

@media (max-width: 480px) {
.horizontal-cell {
    width: 100%;
  }
}

.horizontal-cell:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.item-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #f8f9fa;
}

.item-price {
  font-size: 20px;
  margin-bottom: 15px;
  color: #e6e6e6; 
}

.item-description,
.item-seller,
.item-status {
  font-size: 16px;
  margin-bottom: 15px;
  opacity: 0.8;
  color: #d1d1d1; 
}

.van-button {
  width: 25%;
  background-color: #ffffff;
  color: #2575fc;
  border: 1px solid #ffffff;
  border-radius: 10px;
  padding: 10px;
  text-transform: uppercase;
  letter-spacing: 1px;
  transition: background-color 0.3s, color 0.3s, border-color 0.3s;
}

.van-button:hover {
  background-color: #2575fc;
  color: #ffffff;
  border-color: #2575fc;
}

.success-message {
  color: #28a745;
  font-size: 18px;
  margin-top: 20px;
  margin-bottom: 15px;
}

.error-message {
  color: #dc3545;
  font-size: 18px;
  margin-top: 20px;
  margin-bottom: 15px;
}

.loading-animation {
  margin: 30px auto;
}
</style>